#!/usr/bin/python3
# -*- coding:utf-8 -*-
#python version: 3.6.7

#requests访问网页用的
#time取时间用的
#json解析网站返回数据
#os用来取目录
import time
import json
import os
import sys
#首先获取到脚本所在目录，并把工作目录设为脚本所在目录
cdw = os.path.realpath(__file__)
cdw = os.path.dirname(cdw)
#argv用来获取是否有传入参数
from sys import argv
sys.path.append(sys.path[0][: sys.path[0].rindex('/')])
from librp.visit_website import *
from librp.file_analysis import *
import update_cookies
os.chdir(cdw)

#定义一个打印和输出的函数(print and write html file)
def pawhf(pwstr):
    print(pwstr)
    if os.path.isdir('/var/www/html/zbdd/'):
        f_html = open('/var/www/html/zbdd/index.html', 'w')
    else:
        f_html = open('index.html', 'w')
    t_html = '<html>\n'
    t_html += '\t<head>\n'
    t_html += '\t\t<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />\n'
    t_html += '\t\t<title>zbcc1203 E-commerce Report</title>\n'
    t_html += '\t</head>\n'
    t_html += '\t<body>'
    t_html += pwstr.replace('\n', '<br>\n').replace(' ', '&nbsp;')
    t_html += '\n\t</body>\n</html>'
    f_html.write(t_html)
    f_html.close()
def daily_summary():
    try:
        isdebug = argv[1]
        isdebug = True
    except(IndexError):
        isdebug = False
    zt_text = ['WTF', '京东', '美团', '饿了么']
    #登陆的cookie放在文件中，不放在源码里格式好看一些，也不用每次重新登陆还要改源码

    success_code = {
        'dmall_order' : ['code', 'success'],
        'dmall_absence' : ['code', '0000'],
        'dmall_achievement' : ['code', '0000'],
        'hiboos_order' : ['code', '0'],
        'hiboos_cancel_list' : ['code', '0'],
        'hiboos_absence' : ['code', '0'],
        'jddj' : ['code', '0'],
        'mtwm' : ['code', 0],
        'ele' : ['errors', []]
    }
    errors_url = {
        'dmall' : '来客系统',
        'hiboos' : '海博系统',
        'jddj' : '京东商家中心',
        'mtwm' : '美团外卖商家中心',
        'ele' : '饿了么商家零售版'
    }
    url_names = list(errors_url.keys())
    #循环打开各个文件
    text_curl_str = {i: '../cookies/chrome_curl/curl_' + i + '.sh' for i in url_names}
    for i in url_names:
        #默认的rt方式打开文件在文件不存在时会报异常，所以要上一个try
        try:
            #这里打开curl文件
            file_curl = open(text_curl_str[i])
            #把文件放入变量
            text_curl_str[i] = file_curl.read()
            #文件用完就关闭，防止意外终止
            file_curl.close()
        #报文件不存在异常时的处理
        except FileNotFoundError:
            pawhf('错误！文件{}不存在！！！(0x0000004c)'.format(
                ck_filename[i]
            ))
            exit()
    url_dict = get_url_dict(text_curl_str['mtwm'])
    post_param = get_post_param(text_curl_str['dmall'])
    header_dict = {
        i: curl2header_dict(
            text_curl_str[i]
        )
        for i in url_names
    }
    cookie_dict = {
        i: curl2cookie_dict(
            text_curl_str[i]
        )
        for i in url_names
    }
    in_f = open('input.json')
    in_t = in_f.read()
    in_d = json.loads(in_t)
    in_f.close()
    #循环访问各平台网址
    re_dict = [
        'dmall_order',
        'hiboos_cancel_list',
        'jddj',
        'mtwm',
        'ele',
        'dmall_achievement',
        'dmall_absence',
        'hiboos_order',
        'hiboos_absence'
    ]
    for i in range(6):
        url_key = re_dict[i]
        url_name = url_key\
        if '_' not in url_key\
        else url_key[:url_key.index('_')]
        #访问网址取到网页源码
        html = get_post_html(
            url_dict[url_key],
            header_dict[url_name],
            cookie_dict[url_name],
            post_param.get(url_key)
        )
        #如果出错的话返回值是16个*开头的
        if html[ :16] == '*' * 16:
            pawhf(html + '\nnu:129\nvalue:' + re_dict[i])
            exit()
        try:
            re_dict[i] = json.loads(s = html)
            if isdebug:
                print(i)
                print(re_dict[i])
        except:
            pawhf('出错了!请重新拦截{}的curl信息!(0x00000084)'.format(errors_url[url_name]))
            exit()
        if url_key != 'ele':
            try:
                if re_dict[i][success_code[url_key][0]] != success_code[url_key][1]:
                    pawhf('出错了!请重新拦截{}的curl信息！(0x00000088)'.format(errors_url[url_name]))
                    exit()
            except KeyError:
                pawhf('出错了！请重新拦截{}的curl信息!(0x0000008b)'.format(errors_url[url_name]))
                exit()
    order_quantity, order_amount = [0, 0, 0, 0, 0], [0.0, 0.0, 0.0, 0.0, 0.0]
    for i in range(len(re_dict[0]['data']['data'])):
        j = 1 if re_dict[0]['data']['data'][i]['shipmentTypeDesc'] == '自提' else 0
        order_quantity[j] += 1
        order_amount[j] += float(re_dict[0]['data']['data'][i]['warePriceDesc'])
    order_quantity[2] = int(re_dict[2]['result']['todayFinishOrderNum'])
    order_amount[2] = float(re_dict[2]['result']['todayOrderTurnover'])
    order_quantity[3] = re_dict[3]['data'][1]['currentValue']
    order_quantity[3] = 0 if order_quantity[3] == None else int(order_quantity[3])
    order_amount[3] = re_dict[3]['data'][0]['currentValue']
    order_amount[3] = 0.0 if order_amount[3] == None else float(order_amount[3])
    order_quantity[4] = int(re_dict[4]['valid_order_num']['count'])
    order_amount[4] = float(re_dict[4]['expect_income']['count'])
    #print(order_quantity)
    #print(order_amount)
    hb_cancel = [[], [], [], []]
    if 'resultList' in re_dict[1]['result'].keys():
        hb_cancel_n = len(re_dict[1]['result']['resultList'])
        for i in range(hb_cancel_n):
            hb_channel = int(re_dict[1]['result']['resultList'][i]['channel'])
            hb_cancel[hb_channel].append(int(
                re_dict[1]['result']['resultList'][i]['daySeq']
            ))
    else:
        hb_cancel_n = 0
    for i in range(4):
        hb_cancel[i].sort()
    #print(hb_cancel)
    if len(re_dict[5]['data']['records']) == 0:
        achievement = 0
    else:
        achievement = int(re_dict[5]['data']['records'][0]['val_11'])
    tm_wday = int(time.strftime('%w', time.localtime(time.time())))
    #取各平台置缺信息
    #这是多点的
    url_key = re_dict[6]
    url_name = url_key\
    if '_' not in url_key\
    else url_key[:url_key.index('_')]
    #访问网址取到网页源码
    html = get_post_html(
        url_dict[url_key],
        header_dict[url_name],
        cookie_dict[url_name],
        post_param.get(url_key)
    )
    #如果出错的话返回值是16个*开头的
    if html[ :16] == '*' * 16:
        pawhf(html + '\nnu:194\nvalue:' + re_dict[i])
        exit()
    try:
        re_dict[6] = json.loads(s = html)
        if isdebug:
            print(6)
            print(re_dict[6])
    except:
        pawhf('出错了!请重新拦截{}的curl信息!(0x000000c8)'.format(errors_url[url_name]))
        exit()
    try:
        if re_dict[6][success_code[url_key][0]] != success_code[url_key][1]:
            pawhf('出错了!请重新拦截{}的curl信息！(0x000000cc)'.format(errors_url[url_name]))
            exit()
    except KeyError:
        pawhf('出错了！请重新拦截{}的curl信息!(0x000000cf)'.format(errors_url[url_name]))
        exit()
    oos = ''
    for i in range(re_dict[6]['total']):
        oos += str(re_dict[6]['rows'][i]['itemNum']) + ';'

    #这是海博的，相对就麻烦了
    i = 0
    url_key = re_dict[7]
    url_name = url_key\
    if '_' not in url_key\
    else url_key[:url_key.index('_')]
    while True:
        #用i变量来控制页码，一页页的取出所有数据
        i += 1
        post_param[url_key]['page'] =\
        post_param[url_key]['page'].replace(
            ':{},'.format(i - 1),
            ':{},'.format(i)
        )
        #访问网址取到网页源码
        html = get_post_html(
            url_dict[url_key],
            header_dict[url_name],
            cookie_dict[url_name],
            post_param.get(url_key)
        )
        #如果出错的话返回值是16个*开头的
        if html[ :16] == '*' * 16:
            pawhf(html + '\nnu:238\nvalue:' + re_dict[i])
            exit()
        try:
            re_dict[7] = json.loads(s = html)
            if isdebug:
                print(7)
                print(re_dict[7])
        except:
            pawhf('出错了!请重新拦截{}的curl信息!(0x000000f4)'.format(errors_url[url_name]))
            exit()
        try:
            if re_dict[7][success_code[url_key][0]] != success_code[url_key][1]:
                pawhf('出错了!请重新拦截{}的curl信息！(0x000000f8)'.format(errors_url[url_name]))
                exit()
        except KeyError:
            pawhf('出错了！请重新拦截{}的curl信息!(0x000000fb)'.format(errors_url[url_name]))
            exit()
        time.sleep(2)
        if 'resultList' not in re_dict[7]['result']:
            break
        if re_dict[7]['result']['resultList'] == []:
            break
    '''
        for d in re_dict[7]['result']['resultList']:
            if d['isAdjusted'] != 0:
                html = get_post_html(
                    url_dict['hiboos_absence'],
                    header_dict['hiboos'],
                    cookie_dict['hiboos'],
                    'body=%7B%22orderId%22%3A%22{}%22%7D'.format(d['orderId'])
                )
                #如果出错的话返回值是16个*开头的
                if html[ :16] == '*' * 16:
                    pawhf(html + '\nnu:270\nvalue:' + re_dict[i])
                    exit()
                try:
                    re_dict[8] = json.loads(s = html)
                    if isdebug:
                        print(8)
                        print(re_dict[8])
                except:
                    pawhf('出错了!请重新拦截{}的curl信息!(0x00000111)'.format(errors_url[url_name]))
                    exit()
                try:
                    if re_dict[7][success_code[url_key][0]] != success_code[url_key][1]:
                        pawhf('出错了!请重新拦截{}的curl信息！(0x00000115)'.format(errors_url[url_name]))
                        exit()
                except KeyError:
                    pawhf('出错了！请重新拦截{}的curl信息!(0x00000118)'.format(errors_url[url_name]))
                    exit()
                for d in re_dict[8]['result']['products']:
                    if d['skuAmendNum'] == 1:
                        if len(d['skuUpc']) == 18:
                            absence = d['skuUpc'][2: 7]
                        else:
                            absence = d['skuUpc']
                        if absence not in oos:
                            oos += absence + ';'
    '''
    oos = oos.count(';')
    summary = in_d['store']
    summary += time.strftime('%Y年%m月%d日', time.localtime())
    summary += '电商工作总结\n'
    summary += '1.今日订单(全平台) ：{}单\n'.format(sum(order_quantity))
    summary += '    总营业额{:.2f}元。\n'.format(round(sum(order_amount), 2))
    summary += '    多点订单(o2o):{}单\n'.format(order_quantity[0])
    summary += '    销售额:{:.2f}元\n'.format(order_amount[0])
    summary += '    多点自提:{}单\n'.format(order_quantity[1])
    summary += '    销售额:{:.2f}元\n'.format(order_amount[1])
    summary += '    美团订单：{}单\n'.format(order_quantity[3])
    summary += '    营业额：{:.2f}元\n'.format(order_amount[3])
    summary += '    饿了么订单: {}单\n'.format(order_quantity[4])
    summary += '    营业额：{:.2f}元\n'.format(order_amount[4])
    summary += '    京东到家订单：{}单\n'.format(order_quantity[2])
    summary += '    营业额：{:.2f}元\n'.format(order_amount[2])
    summary += '2.今日履约完成{}单，取消订单{}单'.format(
        sum(order_quantity), hb_cancel_n
    )
    if hb_cancel_n > 0:
        summary += '('
        for i in range(4):
            if len(hb_cancel[i]) == 0:
                continue
            summary += zt_text[i]
            for j in hb_cancel[i]:
                summary += str(j) + '、'
            summary = summary[: -1]
            summary += '，'
        summary = summary[: -1]
        summary += ')，顾客自行取消'
    summary += '\n3.本月拉新目标：'
    summary += '{}人，截至昨日拉新{}人 ，完成率:{:.2%}\n'.format(
        in_d['target'], achievement, achievement / float(in_d['target'])
    )
    summary += '4.今日缺品：{}个\n'.format(oos)
    summary += '5.客诉工单：0单\n'
    summary += '6.售后退款情况：0单\n'
    summary += '7.配送系统：饿了么 京东到家 美团\n'
    if in_d['couriers'][tm_wday] == '无':
        summary += '8.今日配送员人数: 0人\n'
    else:
        summary += '8.今日配送员人数: {}人，{}\n'.format(
            in_d['couriers'][tm_wday].count('、') + 1,
            in_d['couriers'][tm_wday]
        )
    shift = in_d['schedule'].keys()
    summary += '9.今日工作安排:\n'
    for i in shift:
        if in_d['schedule'][i][tm_wday] != '无':
            summary += '    {}：{}\n'.format(
                i,
                in_d['schedule'][i][tm_wday]
            )
    summary += '10.明日人员安排：\n'
    for i in shift:
        if in_d['schedule'][i][tm_wday + 1] != '无':
            summary += '    {}：{}\n'.format(
                i,
                in_d['schedule'][i][tm_wday + 1]
            )
    summary += '11.今日配送订单是否闭环；是\n'
    summary += '12.如有取消订单请写明原因:0单缺货，'
    summary += '其余{}单顾客无理由取消订单；\n'.format(hb_cancel_n)
    summary += '13.本月拉新目标：'
    summary += '{}人，截至昨日拉新{}人 ，完成率:{:.2%}'.format(
        in_d['target'], achievement, achievement / float(in_d['target'])
    )
    pawhf(summary)
    return summary
if __name__ == "__main__":
    daily_summary()
